package com.weibo.basic.alg.alert.server.service;

import com.weibo.basic.alg.alert.server.config.WechatConfig;
import com.weibo.basic.alg.alert.server.domain.RefreshAccessTokenReturn;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import retrofit2.Response;

@Service
@Slf4j
public class TokenService {

    private AtomicReference<String> tokenRef = new AtomicReference<>();
    @Autowired
    private WechatAPI wechatAPI;

    @Autowired
    private WechatConfig wechatConfig;

    public String getToken(boolean refresh) throws IOException {
        if (refresh || tokenRef.get() == null) {
            synchronized (this) {
                Response<RefreshAccessTokenReturn> ret = wechatAPI
                    .getToken(wechatConfig.getCorpid(), wechatConfig.getCorpsecret()).execute();
                if (!ret.isSuccessful()) {
                    log.error("getToken failed,error is {}", ret.raw().message());
                } else {
                    RefreshAccessTokenReturn tokenReturn = ret.body();
                    if (!tokenReturn.isSuccess()) {
                        log.error("getToken failed,error is {}", tokenReturn);
                    } else {
                        tokenRef.set(tokenReturn.getAccess_token());
                    }
                }
            }
        }
        return tokenRef.get();
    }
}
